package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取拦截的路径
        String requestURI = request.getRequestURI();
        //需要放行的路径
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        boolean flag=check(urls,requestURI);
        //如果为True就放行
        if(flag){
            return true;
        }

        //需要处理的用户判断是否登录
        if(request.getSession().getAttribute("employee")!=null){
            //登录放行的路径
            log.info("登录放行的路径{}",requestURI);

            //把用户的id放到threalocal线程域中
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            return true;
        }

        //移动端需要处理的用户判断是否登录
        if(request.getSession().getAttribute("user")!=null){
            //登录放行的路径
            log.info("登录放行的路径{}",requestURI);

            //把用户的手机号放到threalocal线程域中
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            return true;
        }


        //未登录的路径
        log.info("未登录的路径{}",requestURI);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    /**
     * 判断拦截的路径是否
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : urls) {
            boolean flag = antPathMatcher.match(url, requestURI);
            if(flag){
                return true;
            }
        }
        return false;
    }
}
